/*
*/

/**
 * Plugin for inserting files from elFinder without image dialog
 */
( function() {
  CKEDITOR.plugins.add( 'elfinder',
  {
    init: function( editor )
    {
      //adding button 
      editor.ui.addButton( 'elFinder',
      {
        label: 'elFinder',
        command: 'elfinderWindow',
        icon: this.path + 'images/icon.png'
      });
    
      //opening elFinder window
      editor.addCommand( 'elfinderWindow', {
        exec : function () {
          var width = editor.config.filebrowserWindowWidth || '80%',
            height = editor.config.filebrowserWindowHeight || '70%';
          
          editor.popup(Drupal.settings.basePath + 'elfinder?app=ckeditor|sendto@ckeditor_setFinderFile|&CKEditorFuncNum=' + editor._.filebrowserFnFinder + '&langCode=ru', width, height);
        }
      });
      
      //add editor function
      editor._.filebrowserFnFinder = CKEDITOR.tools.addFunction( setFinderFile, editor )
      
      //function which receive elFinder response
      window.ckeditor_setFinderFile = function (file, win) {
        var cfunc = win.location.href.split('&');
      
        for (var x in cfunc) {
          if (cfunc[x].match(/^CKEditorFuncNum=\d+$/)) {
            cfunc = cfunc[x].split('=');
            break;
          }
        }
        CKEDITOR.tools.callFunction(cfunc[1], file);
        win.close();
      };
	  
    }
  } );
  
  function setFinderFile(file) {
	// if file is image
	if (file.match(/.*(.jpg|.png|.jpeg|.gif)$/i)){
      this.insertHtml('<img src="' + file + '" alt="' + file + '" />');
	}
	else
	{
      this.insertHtml('<a href="' + file + '">' + file + '</a>');
	}
  }
  
} )();
